<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;

class UserController extends CommonController {
    private static $USER='user';
    private static $USER_ROLE='user_role';
    private static $SALT_DIY='lan';
    public function getUserList(Request $request){
        $page=$request->get('page')?$request->get('page'):self::$Page;
        $limit=$request->get('limit')?$request->get('limit'):self::$Limit;
        $res=DB::table('user as a')
            ->leftJoin('user_role as b','a.id','=','b.user_id')
            ->leftJoin('role as c','c.id','=','b.role_id')
            ->where('a.delete_flag','=',0)
            ->where('b.delete_flag','=',0)
            ->where('c.delete_flag','=',0)
            ->where(function ($query)use ($request){
                $query->where('a.delete_flag','=',0);
                if ($request->get('name')!=null||!empty($request->get('name'))){
                    $query->where('a.account','like','%'.$request->get('name').'%');
                }
                if ($request->get('role')!=null||!empty($request->get('role'))){
                    $query->where('c.name','like','%'.$request->get('role').'%');
                }
            })
            ->select('a.id','a.account','a.status','a.login_time','c.id as role_id','c.name as role_name','a.info','a.ava_url')
            ->paginate($limit,'','',$page)
            ->toArray();

        return $this->ReturnJson(200,'success',$res);
    }

    public function addUser(Request $request){
        $res=$request->all();
        $roles=[
            'account' => 'required|max:10',
            'password' => 'required',
            'repassword' => 'required',
            'role_id' => 'required',
            'info' => 'required',

        ];
        $messages = [
            'account.required' => '账号不能为空',
            'account.max' => '账号最长十个字符',
            'password.required' => '密码不能为空',
            'repassword.required' => '重复密码不能为空',
            'role_id.required' => '请选择角色',
            'info.required' => '请输入权限简介',
        ];
        $validator =Validator::make($res,$roles,$messages);
        if ($validator->fails()) {
            return $this->ReturnJson(-1,$validator->errors()->first(),'');
        }
        if (!isset($res['ava_url'])||empty($res['ava_url'])){
            $res['ava_url'] = 'http://dns.shmilyi.cn/1622683110.jpeg';
        }
        $is_exit=DB::table(self::$USER)
            ->where('delete_flag','=',0)
            ->where('account','=',$request->get('account'))
            ->exists();
        if ($is_exit){
            return $this->ReturnJson(-1,'账号已存在','');
        }
        if ($request->get('password')!=$request->get('repassword')) {
            return $this->ReturnJson(-1,'两次密码不一致','');
        }
        $salt=$this->GetRandStr(5);
        $password=self::$SALT_DIY.$res['password'].$salt;
        //拿到前端传的加密密码 进行二次加密
        $passHash = password_hash($password, PASSWORD_DEFAULT);
        $insert_data=['account'=>$res['account'],'info'=>$res['info'],'ava_url'=>$res['ava_url'],'password'=>$passHash,'salt'=>$salt,'created_by'=>$this->getUserId($request->header('token')),'created_time'=>date('Y-m-d H:i:s',time())];
        try {
            DB::beginTransaction();
            $user_id=DB::table(self::$USER)->insertGetId($insert_data);
            DB::table(self::$USER_ROLE)->insert(['user_id'=>$user_id,'role_id'=>$res['role_id'],'created_by'=>$this->getUserId($request->header('token')),'created_time'=>date('Y-m-d H:i:s',time())]);
            DB::commit();
            return $this->ReturnJson(200,'添加成功','');
        }catch (\Exception $e){
            DB::rollBack();
            return $this->ReturnJson(-1,$e->getMessage(),'');
        }
    }

    public function updateUser(Request $request){
        $res=$request->all();
        $roles=[
            'account' => 'required|max:10',
            'role_id' => 'required',
            'id' => 'required',
            'info'=>'required',

        ];
        $messages = [
            'account.required' => '账号不能为空',
            'account.max' => '账号最长十个字符',
            'role_id.required' => '请选择角色',
            'id.required' => '缺少参数',
            'info.required' => '请输入角色简介',
        ];
        $validator =Validator::make($res,$roles,$messages);
        if ($validator->fails()) {
            return $this->ReturnJson(-1,$validator->errors()->first(),'');
        }
        if (!isset($res['ava_url'])||empty($res['ava_url'])){
            $res['ava_url'] = 'http://dns.shmilyi.cn/1622683110.jpeg';
        }
        //验证账号唯一性
        $is_exit=DB::table(self::$USER)
            ->where('id','<>',$res['id'])
            ->where('delete_flag','=',0)
            ->where('account','=',$res['account'])
            ->exists();
        if ($is_exit){
            return $this->ReturnJson(-1,'账号已存在,请更换账号名','');
        }
        //判断是否需要更换密码
        if ((isset($res['password'])&&isset($res['repassword']))||(!empty($res['password'])&&!empty($res['repassword']))) {
            $salt=$this->GetRandStr(5);
            $password=self::$SALT_DIY.$res['password'].$salt;
            $passHash = password_hash($password, PASSWORD_DEFAULT);
            $update_data=['account'=>$res['account'],'info'=>$res['info'],'ava_url'=>$res['ava_url'],'password'=>$passHash,'salt'=>$salt,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())];
        }else{
            $update_data=['account'=>$res['account'],'info'=>$res['info'],'ava_url'=>$res['ava_url'],'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())];
        }
        try {
            DB::beginTransaction();
            DB::table(self::$USER)->where('id','=',$res['id'])->update($update_data);
            DB::table(self::$USER_ROLE)->where('user_id','=',$res['id'])->update(['role_id'=>$res['role_id'],'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            DB::commit();
            return $this->ReturnJson(200,'修改成功','');
        }catch (\Exception $e){
            DB::rollBack();
            return $this->ReturnJson(-1,$e->getMessage(),'');
        }
    }

    public function deleteUser(Request $request){
        $id=$request->get('id');
        if (!$id){
            return $this->ReturnJson(-1,'参数错误','');
        }
        try {
            DB::beginTransaction();
            DB::table(self::$USER)->where('id','=',$id)->update(['delete_flag'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            DB::table(self::$USER_ROLE)->where('user_id','=',$id)->update(['delete_flag'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            DB::commit();
            return $this->ReturnJson(200,'删除成功','');
        }catch (\Exception $e){
            DB::rollBack();
            return $this->ReturnJson(-1,$e->getMessage(),'');
        }
    }

    public function CheckUserStatus(Request $request){
        $id=$request->get('id');
        $status=$request->get('status');
        try {
            DB::beginTransaction();
            DB::table(self::$USER)->where('id','=',$id)->update(['status'=>$status,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            DB::commit();
            return $this->ReturnJson(200,'修改成功','');
        }catch (\Exception $e){
            DB::rollBack();
            return $this->ReturnJson(-1,$e->getMessage(),'');
        }
    }
}
